package com.yoyo.yyadsdk.serv;

import android.app.IntentService;
import android.content.Context;
import android.content.Intent;
import android.os.Environment;
import android.os.IBinder;

import androidx.annotation.Nullable;

import com.downloader.Error;
import com.downloader.OnDownloadListener;
import com.downloader.OnProgressListener;
import com.downloader.PRDownloader;
import com.downloader.Progress;
import com.yoyo.yyadsdk.util.ActivityUtils;
import com.yoyo.yyadsdk.util.LogHelper;

import java.io.File;
import java.util.UUID;


/**
 * Author Dollkey
 * Date 2018/5/14 19:35.
 */
public class DownLoadAPKService extends IntentService {

    public static final String TAG = "DownLoadAPKService";
    public static final String PARAM_APK_URL = "apk";
    public static final String PARAM_APK_PACKAGE_NAME = "packageName";
    private Context mContext;
    private int mDownloaderId;
    private String mFileName;
    private String mPackageName;
    private long mCurrentTimeMillis;

    public DownLoadAPKService() {
        super("DownLoadAPKService");
    }

    @Override
    public IBinder onBind(Intent arg0) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        mContext = this;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    protected void onHandleIntent(@Nullable Intent intent) {
        if (intent == null) return;
        mPackageName = intent.getStringExtra(PARAM_APK_PACKAGE_NAME);
        mFileName = UUID.randomUUID().toString().concat(".apk");
        mCurrentTimeMillis = System.currentTimeMillis();
        LogHelper.d("autoInstallApk___url:" + intent.getStringExtra(PARAM_APK_URL));
        mDownloaderId = PRDownloader.download(intent.getStringExtra(PARAM_APK_URL),
                Environment.getExternalStorageDirectory().getAbsolutePath()
                        .concat(File.separator).concat(Environment.DIRECTORY_DOWNLOADS), mFileName).build()
                .setOnProgressListener(new OnProgressListener() {
                    @Override
                    public void onProgress(Progress progress) {
                        if (System.currentTimeMillis() - mCurrentTimeMillis > 200)
                            LogHelper.d("autoInstallApk___progress:" + progress.toString());
                    }
                })
                .start(new OnDownloadListener() {
                    @Override
                    public void onDownloadComplete() {
                        try {
                            LogHelper.d("autoInstallApk___success:" + mPackageName);
                            String fileName = Environment.getExternalStorageDirectory().getAbsolutePath().concat(File.separator)
                                    .concat(Environment.DIRECTORY_DOWNLOADS).concat(File.separator).concat(mFileName);
//                            ActivityUtils.install(fileName);
//                            ActivityUtils.autoInstallApk();
                            ActivityUtils.autoInstallApk(mContext, new File(fileName), mPackageName);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onError(Error error) {
                        LogHelper.d("autoInstallApk___error:" + error.toString());
                        cancelDownLoad();
                    }
                });
        LogHelper.d("autoInstallApk___start:" + intent.getStringExtra(PARAM_APK_URL));
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    private void cancelDownLoad() {
        if (mDownloaderId > 0) {
            PRDownloader.cancel(mDownloaderId);
        }
        mDownloaderId = 0;
        File apk = new File(Environment.getExternalStorageDirectory().getAbsolutePath()
                .concat(File.separator)
                .concat(Environment.DIRECTORY_DOWNLOADS), mFileName);
        File temp = new File(Environment.getExternalStorageDirectory().getAbsolutePath()
                .concat(File.separator)
                .concat(Environment.DIRECTORY_DOWNLOADS), mFileName.concat(".temp"));
        if (apk.exists()) {
            apk.delete();
        }
        if (temp.exists()) {
            temp.delete();
        }
    }
}
